#version 450
#extension GL_ARB_separate_shader_objects : enable

layout(binding = 0) uniform UniformBufferObject {
    mat4 projection;
	mat4 model;
	mat4 invModel;
} ubo;

layout(binding = 1) uniform sampler2D samplerEnvMap;

layout(binding = 2) uniform Exposure {
	float exposure;
} exposure;

layout (location = 0) in vec3 inPos;
layout (location = 1) in vec3 inNormal;

layout(location = 0) out vec4 outColor0;
layout(location = 1) out vec4 outColor1;

layout (constant_id = 0) const int type = 0;

const vec2 invAtan = vec2(0.1591, 0.3183);
vec2 SampleSphericalMap(vec3 v)
{
    vec2 uv = vec2(atan(v.z, v.x), asin(v.y));
    uv *= invAtan;
    uv += 0.5;
    return uv;
}


void main() {

	vec2 uv;

    switch(type)
	{
		case 0: // skybox
			vec3 normal = normalize(inNormal);
			uv = SampleSphericalMap(normal);
			break;
		case 1: // reflect
			vec3 cI = normalize(inPos);
			vec3 cR = reflect(cI, normalize(inNormal));
			cR = vec3(ubo.invModel * vec4(cR, 0.0));
			// Convert cubemap coordinates into Vulkan coordinate space
			cR.xy *= -1.0;
			uv = SampleSphericalMap(cR);
			break;
	}

	vec4 envColor = texture(samplerEnvMap, uv);

    // Color with manual exposure into attachment 0
	outColor0.rgb = vec3(1.0) - exp(-envColor.rgb * exposure.exposure);

	// Bright parts for bloom into attachment 1
	float l = dot(outColor0.rgb, vec3(0.2126, 0.7152, 0.0722));
	float threshold = 0.75;
	outColor1.rgb = (l > threshold) ? outColor0.rgb : vec3(0.0);
	outColor1.a = 1.0;
}